package com.chx.three.mama.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chx.three.mama.R;
import com.chx.three.mama.view.Topbar;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;

@ContentView(R.layout.activity_add_diary)
public class AddDiaryActivity extends Activity implements View.OnClickListener, Topbar.onTopbarClickListener {

    private static final String TAG = "AddDiaryActivity";
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int PICK_IMAGE_ACTIVITY_REQUEST_CODE = 200;

    @ViewInject(R.id.diary_content)
    EditText mContent;
    @ViewInject(R.id.camera)
    ImageView mCamera;
    @ViewInject(R.id.now_time)
    TextView mNowTime;
    @ViewInject(R.id.camera_layout)
    LinearLayout mLayout;
    @ViewInject(R.id.camera_img)
    ImageView mImage;;
    @ViewInject(R.id.add_diary_topbar)
    Topbar topbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);

        mCamera.setOnClickListener(this);
        topbar.setOnTopbarClickListener(this);

        Calendar calendar = Calendar.getInstance();
        String mMonth = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        String mDay = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        String mTime = mMonth + "月" + mDay + "日";
        mNowTime.setText(mTime);

    }

    private static String picFileFullName;

    @Override
    public void onClick(View v) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder
                .setItems(new String[]{"从相册选取", "拍照获取"},
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                                        intent.setType("image/*");
                                        intent.putExtra("return-data", true);

                                        startActivityForResult(intent, PICK_IMAGE_ACTIVITY_REQUEST_CODE);
                                        break;
                                    case 1:
                                        String state = Environment.getExternalStorageState();
                                        if (state.equals(Environment.MEDIA_MOUNTED)) {
                                            Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                            File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                            if (!outDir.exists()) {
                                                outDir.mkdirs();
                                            }
                                            File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                                            picFileFullName = outFile.getAbsolutePath();
                                            intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                                            intent2.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                            startActivityForResult(intent2, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                                        } else {
                                            Log.e(TAG, "请确认已经插入SD卡");
                                        }
                                        break;
                                }
                            }
                        }
                );


        AlertDialog dialog = builder.create();

        dialog.show();


    }

    private Bitmap bitmap;
    private String jpg;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_IMAGE_ACTIVITY_REQUEST_CODE) {
            if(resultCode == RESULT_OK) {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                try {
                    bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                    if (bitmap != null) {
                        mLayout.setVisibility(View.VISIBLE);
                        mImage.setImageBitmap(bitmap);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }else if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE){
            if(resultCode == RESULT_OK){
                bitmap = BitmapFactory.decodeFile(picFileFullName);
                if(bitmap != null) {
                    mLayout.setVisibility(View.VISIBLE);
                    mImage.setImageBitmap(bitmap);
                }
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onLeftButtonClick() {

    }

    @Override
    public void onRightButtonClick() {
        String url = "http://baby.ci123.com/yunqi/ios2/diary_add_v2.php";
        RequestParams params = new RequestParams();
        params.addBodyParameter("content",mContent.getText().toString());
        params.addBodyParameter("site","61");
        params.addBodyParameter("o_user_id","4268783");
        if(jpg != null){
            params.addBodyParameter("pic_0",jpg);
        }

        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.d("TAG","result：" + result);
                        Intent intent = new Intent(AddDiaryActivity.this,FeelingDailyActivity.class);
                        startActivity(intent);
                        Toast.makeText(AddDiaryActivity.this, "发布成功", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(AddDiaryActivity.this, "发布失败", Toast.LENGTH_LONG).show();

                    }
                }
        );
    }

    @Override
    public void onSearchButtonClick() {

    }
}
